package com.nimlib.adapter;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.databinding.AdapterImMsgContentBinding;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.nimlib.emoji.MoonUtil;
import com.nimlib.utils.NimIMUtils;
import com.nimlib.utils.NimUserInfoCache;

import java.util.List;

import me.nereo.multi_image_selector.utils.TimeUtils;

/**
 * 最近联系人列表
 */
public class IMMsgListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<RecentContact> list;
    private Context mContext;
    private String ownAccount; //自己的云信账号
    public IMMsgListAdapter(Context context,String ownAccount,List<RecentContact> list){
        this.mContext = context;
        this.list = list;
        this.ownAccount = ownAccount;
    }

    private final int TYPE_EMPTY = 1;
    private final int TYPE_ITEM = 2;

    public void updateList(List<RecentContact> list){
        NimUserInfoCache.getInstance().buildCache();
        this.list.clear();
        this.list.addAll(list);
        this.notifyDataSetChanged();
    }


    public void addItemAtFirst(RecentContact contact){
        NimUserInfoCache.getInstance().buildCache();
        list.add(0,contact);
        this.notifyDataSetChanged();
    }

    public boolean notifyItem(RecentContact recentContact){
        boolean flag=false;
        for (int i = 0; i < list.size(); i++) {
            RecentContact contact = list.get(i);
            if (recentContact!= null && TextUtils.equals(contact.getContactId(),recentContact.getContactId())){
                list.remove(contact);
                list.add(0,recentContact);
                flag = true;
                break;
            }
        }
        if (flag){
            NimUserInfoCache.getInstance().buildCache();
            this.notifyDataSetChanged();
        }
        return flag;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        if (viewType==TYPE_EMPTY){
            return new EmptyViewHolder(inflater.inflate(R.layout.adapter_im_empty_layout, parent, false));
        }
        return new ItemViewHolder(inflater.inflate(R.layout.adapter_im_msg_content,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder){
            bindItemViewHolder((ItemViewHolder) holder,position);
        }
    }

    private void bindItemViewHolder(ItemViewHolder holder, int position) {
        AdapterImMsgContentBinding binding = DataBindingUtil.getBinding(holder.itemView);
        RecentContact contact = list.get(position);
        NimUserInfo userInfo = NimUserInfoCache.getInstance().getUserInfo(contact.getContactId()); //最近联系人信息
        if (userInfo==null){
            NimIMUtils.fetchUserInfo(contact.getContactId(), new RequestCallbackWrapper<List<NimUserInfo>>() {
                @Override
                public void onResult(int code, List<NimUserInfo> result, Throwable exception) {
                    if (code==200 && result.size() == 1){
                        showItem(result.get(0),binding,contact);
                    }else {
                        binding.nickName.setText(Html.fromHtml("<font color='red'>无效用户</font>"));
                    }
                }
            });
        }else {
            showItem(userInfo,binding,contact);
        }
    }

    private void showItem(NimUserInfo finalUserInfo,AdapterImMsgContentBinding binding,RecentContact contact){
        Glide.with(mContext).load(finalUserInfo.getAvatar()).placeholder(R.mipmap.ic_role_head).into(binding.userAvatarImageView);
        String time = TimeUtils.formatPhotoDate(contact.getTime());
        binding.timeLabel.setText(time);
        binding.unreadTip.setVisibility(View.GONE);
        //region 检查已读状态
        NimIMUtils.queryMessage(new RequestCallbackWrapper<List<IMMessage>>() {
            @Override
            public void onResult(int code, List<IMMessage> result, Throwable exception) {
                if (result!=null && result.size()>0){
                    IMMessage message = result.get(0);
                    String content = message.getContent();
                    if (TextUtils.equals(message.getFromAccount(),ownAccount) && !message.isRemoteRead()){
//                        binding.unreadTip.setVisibility(View.VISIBLE);
                    }else {
                        binding.unreadTip.setVisibility(View.GONE);
                    }
                    if (message.getMsgType()== MsgTypeEnum.custom){
                        binding.content.setText(content);
                    }else {
                        MoonUtil.identifyFaceExpression(mContext, binding.content, contact.getContent(), ImageSpan.ALIGN_BOTTOM);
                    }
                }
            }
        },contact.getRecentMessageId());
        //endregion
        binding.nickName.setText(finalUserInfo.getName());
        if (listener!=null){
            binding.rootView.setOnClickListener(v->listener.onItemClick(finalUserInfo,contact));
        }

        int count = contact.getUnreadCount();
        if (count!=0){
            binding.dropFake.setText(String.valueOf(contact.getUnreadCount()));
        }else {
            binding.dropFake.setText(null);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (list==null || list.isEmpty()){
            return TYPE_EMPTY;
        }
        return TYPE_ITEM;
    }

    public List<RecentContact> getItems(){
        return this.list;
    }

    @Override
    public int getItemCount() {
        if (list==null || list.isEmpty()){
            return 1;
        }
        return list.size();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder{

        ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    class EmptyViewHolder extends RecyclerView.ViewHolder{

        EmptyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public void setItemClickListener(ItemClickListener listener){
        this.listener = listener;
    }

    private ItemClickListener listener;

    public interface ItemClickListener{
        void onItemClick(NimUserInfo userInfo,RecentContact contact);
    }
}
